package cn.edu.tju.elm.repository;

import cn.edu.tju.elm.model.Order;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface OrderRepository extends JpaRepository<Order, Long> {
    /**
     * 根据用户ID查询订单列表，包含关联实体
     */
    @Query("SELECT o FROM Order o " +
            "LEFT JOIN FETCH o.customer " +
            "LEFT JOIN FETCH o.business b " +
            "LEFT JOIN FETCH b.businessOwner " +
            "LEFT JOIN FETCH o.deliveryAddress d " +
            "LEFT JOIN FETCH d.customer " +
            "WHERE o.customer.id = :userId " +
            "ORDER BY o.orderDate DESC")
    List<Order> findByCustomerIdWithDetails(@Param("userId") Long id);
    @Query("SELECT o FROM Order o LEFT JOIN FETCH o.customer c LEFT JOIN FETCH o.business b LEFT JOIN FETCH o.deliveryAddress d WHERE o.id = :id")
    Order findOrderById(@Param("id") Long id);

    List<Order> findByCustomerId(Long customerId);
    List<Order> findByBusinessId(Long businessId);
    List<Order> findByCustomerIdAndOrderState(Long customerId, Integer orderState);

    @Query("SELECT o FROM Order o JOIN FETCH o.business b " +
            "JOIN FETCH b.businessOwner " +
            "WHERE b.businessOwner.id = :ownerId " +
            "AND o.orderState IN :states " +
            "ORDER BY o.orderDate DESC")
    List<Order> findByBusinessOwnerIdAndOrderStateIn(
            @Param("ownerId") Long ownerId,
            @Param("states") List<Integer> states);

}
